# data_generation/traffic_data.py
import numpy as np
import pandas as pd
from datetime import datetime, timedelta
from confg import Config


class TrafficDataGenerator:
    def __init__(self):
        self.config = Config()

    def generate_dates(self):
        end_date = datetime.today()
        start_date = end_date - timedelta(days=self.config.DAYS_BACK)
        return [start_date + timedelta(days=x) for x in range(self.config.DAYS_BACK + 1)]

    def generate_traffic_data(self):
        dates = self.generate_dates()
        data = []

        # 创建产品概率分布（让某些产品更受欢迎）
        product_probs = np.array([0.15, 0.18, 0.2, 0.1, 0.12, 0.08, 0.07, 0.1])
        product_probs = product_probs / product_probs.sum()  # 归一化

        for date in dates:
            for device in self.config.DEVICES:
                for source in self.config.SOURCES:
                    # 基础流量（不同来源有不同基数）
                    base_visits = {
                        'Direct': 80,
                        'Organic Search': 150,
                        'Social Media': 120,
                        'Email': 60,
                        'Referral': 90,
                        'Paid Ads': 200
                    }

                    # 波动范围
                    variation = np.random.randint(30, 100)

                    visits = base_visits[source] + variation
                    bounce_rate = np.random.uniform(0.3, 0.7)
                    avg_duration = np.random.uniform(0.5, 10)

                    # 转化率：不同来源有不同转化率
                    base_conversion = {
                        'Direct': 0.04,
                        'Organic Search': 0.035,
                        'Social Media': 0.025,
                        'Email': 0.05,
                        'Referral': 0.03,
                        'Paid Ads': 0.02
                    }

                    conversion_rate = base_conversion[source] * np.random.uniform(0.8, 1.2)

                    # 生成热门产品
                    top_products = np.random.choice(
                        self.config.PRODUCTS,
                        3,
                        replace=False,
                        p=product_probs
                    )

                    # 添加周末效应
                    if date.weekday() in [5, 6]:  # 周六、周日
                        visits = int(visits * 1.3)
                        avg_duration = avg_duration * 1.2

                    data.append({
                        'date': date,
                        'device_type': device,
                        'traffic_source': source,
                        'visits': visits,
                        'bounce_rate': bounce_rate,
                        'avg_session_duration': avg_duration,
                        'conversion_rate': conversion_rate,
                        'top_product_1': top_products[0],
                        'top_product_2': top_products[1],
                        'top_product_3': top_products[2]
                    })

        return pd.DataFrame(data)